<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * 产品模型
 * @author www.dingwei.cn
 */

class ConsumerProductModel extends MY_Model{
	
	public $tbProduct = 'product';
	public $tbProductDetail= 'product_detail';//商品详情
	public $tbCategory= 'product_category';//平台分类
	public $tbProductCustomCategory = 'product_custom_category';//自定义分类
	public $tbProductProperty = 'product_property';//标签属性
	public $tbProductVariant= 'product_variant';//标签属性组合
	public $tbOrder = 'consumer_order';//订单
	public $tbOrderProduct = 'consumer_order_product';//订单产品
	public $tbCart = 'consumer_cart';//购物车
    public $tbTags= 'product_tags';// 属性

	function __construct(){
		parent::__construct();
	}

	/**
	 * app获取商品列表
	 * @param integer $merchantId	商家id
	 * @param integer $customId		自定义分类id
	 * @param integer $order		排序 1销量最高 2库存最少 3上架中 4下架中
	 * @param number $page
	 * @author zyl
	 */
	public function appGetList($merchantId, $customId, $page = 1, $order = 0,$mini = false){
		if ( ! $merchantId || ! $customId ){
			return array();
		}

		if($order == 1){
		    $this->db->order_by('sale_quantity desc,sort asc,addtime desc');
        }elseif ($order == 2){
            $this->db->order_by('quantity asc,sort asc,addtime desc');
        }elseif ($order == 3){
            $this->db->where('status', 2);
            $this->db->order_by('sort asc,addtime desc');
        }elseif ($order == 4){
            $this->db->where('status', 1);
            $this->db->order_by('sort asc,addtime desc');
        }else{
            $this->db->order_by('sort asc,addtime desc');
        }

		if($mini){//@author khj
            $this->db
                ->select('id,name,status,sale_quantity,goods_price,market_price,icon,quantity,is_limited')
                ->where('merchant_id',$merchantId)
                ->where('category_id',$customId)
                ->where_in('status', array(0,1,2));
            $tA = $this->appPage($this->tbProduct, $page);

            foreach ($tA['list'] as $k=>$v){
                $tA['list'][$k]['icon'] = getImage($v['icon']);
                if($v['is_limited'] == 2){
                    $tA['list'][$k]['quantity'] = '无限';
                }
            }

            return $tA['list'];
        }

        $this->db
            ->select('id,name,sale_quantity,goods_price,market_price,icon')
            ->where('merchant_id',$merchantId)
            ->where('category_id',$customId)
            ->where('status',2);

        $tA = $this->appPage($this->tbProduct, $page);

		foreach ($tA['list'] as $k=>$v){
			$tA['list'][$k]['icon'] = getImage($v['icon']);
		}
		
		return $tA['list'];
	}

	/**
	 * app获取商品列表
	 * @param integer $merchantId	商家id
	 * @param integer $customId		自定义分类id
	 * @param integer $down		是否自动下架库存为0 的商品
	 * @param number $page
	 * @author zyl
	 */
	public function appGetAll($merchantId,$userId = 0, $down = false){
		if ( ! $merchantId){
			return array();
		}
		
		$this->db
		->select('p.id,p.name,p.sale_quantity,p.is_special,p.is_limited,p.quantity,p.category_id,p.goods_price,p.market_price,
		            p.limit_number,p.discount,p.icon,0 as u_quantity,0 as u_sort,v.v_is_limited,v.v_quantity,v.sort')
		->where('p.merchant_id',$merchantId)
		->where('p.status',2);
		if ($userId){
			$this->db->select('SUM(c.quantity) as u_quantity,c.variant_id as u_sort');
			$this->db->join($this->tbCart.' c','c.product_id = p.id and c.consumer_id='.$userId,'left');
		}
		if($down){
            $this->db->join('(select sort,product_id,is_limited as v_is_limited,quantity as v_quantity from '.$this->tbProductVariant .' order by product_id desc,is_limited desc,quantity desc)'.'  v','v.product_id = p.id','left');
        }
		$this->db->group_by('p.id');
		$this->db->order_by('p.sort asc,p.id asc');
		$tA = $this->getAll($this->tbProduct.' p');
// 		echo $this->db->last_query();
        $downProduct = array();

		foreach ($tA as $k=>&$v){
            $v['quantity'] = $v['is_limited'] == 1 ? $v['quantity'] : "999";//无限库存
            $tA[$k]['u_quantity'] = empty($v['u_quantity'])?"0":$v['u_quantity'];
            $tA[$k]['u_sort'] = empty($v['u_sort'])?"0":$v['u_sort'];
            $tA[$k]['icon'] = getImage($v['icon']);
            //限购
            if($v['limit_number'] && $v['discount']){
                $v['market_price'] = $v['goods_price'];
                $v['goods_price'] = sprintf('%.2f',($v['goods_price'] * $v['discount'])/10);

            }
		    if($v['sort']>0 && $v['v_is_limited'] == 0 && $v['v_quantity'] == 0){
		        //库存为0 下架商品
                $downProduct[] = array(
                    'id' => $v['id'],
                    'status' => 1
                );
                unset($tA[$k]);
            }else{
                if($v['is_limited'] == 1 && $v['quantity'] == 0){
                    //库存为0 下架商品
                    $downProduct[] = array(
                        'id' => $v['id'],
                        'status' => 1
                    );
                    unset($tA[$k]);
                }
            }

		}
		if($downProduct){
            //库存为0 下架商品
            $this->saveBatchProduct($downProduct,'id');
        }
//p($tA);
		return $tA;
	}

    public function searchProductByKeyword($keyword,$merchantId)
    {
        if (!$keyword) return array();
        $this->db;
        $this->db->select('p.id,p.merchant_id,p.name')
            ->like('p.name', $keyword)
            ->where('p.merchant_id', $merchantId)
            ->where('p.status', 2);
        $tA = $this->getAll($this->tbProduct.' p');
        return $tA;
    }
	
    /**
     * 获取自定义分类下商品数量
     * @param $customIds    分类id
     * @param int $merchantId  商户id
     * @return string|int
     * @author khj
     */
	public function getCustomProductCount($customIds, $merchantId = 0){
	    if(!$customIds) return '';

        if($merchantId){
            $this->db->where('merchant_id', $merchantId);
        }
        $this->db->select('category_id,count(id) as total')
	            ->where_in('category_id', $customIds)
                ->where_in('status', array(0,1,2))
                ->group_by('category_id');
        $tA = $this->getAll($this->tbProduct);

        $data = array();
        foreach ($tA as $v){
            $data[$v['category_id']] = $v['total'];
        }

        return $data;
    }

    /**
     *
     * 获取产品信息
     * @param $id
     * @param int $merchantId
     * @return array
     */
	public function getInfo($id, $merchantId = 0, $mini = false, $detail = false){
		if ( ! $id){
			return array();
		}
		if ($merchantId){
			$this->db->where('merchant_id',$merchantId);
		}
		
		if($mini){
			$this->db
				  ->select('id,name,icon,sale_quantity,goods_price,weight,is_limited,merchant_id,limit_number,quantity,status');
		}else{
			$this->db
				  ->select('id,name,subtitle,sale_quantity,market_price,goods_price,lunch_box_fee,weight,is_free_shipping,img,icon,category_id,merchant_id,
			      is_limited,is_special,quantity,status,addtime,lunch_box_fee,limit_number,discount');
		}
		
		$this->db->where('id',$id)
            ->where('status  > -1');
		$tA = $this->getOne($this->tbProduct);
		if ($tA){
			if( ! $mini){
				$img = json_decode($tA['img'],true);
                $tA['img'] = array();
                if ($img){
                    foreach ($img as $k=>$v){
                        $tA['img'][] = getImage($v,'og');
                    }
                }
				
				$tA['quantity'] = $tA['is_limited'] == 2?'999':$tA['quantity'];//如果商品的库存量是无限 则设置为999
				$tA['icon'] = getImage($tA['icon']);
			}
			$tA['discount'] = isset($tA['discount'])?$tA['discount']:'0';
			$tA['limit_number'] = isset($tA['limit_number'])?$tA['limit_number']:'0';
			if($tA['limit_number'] && $tA['discount'] && $detail == false){
			    $tA['market_price'] = $tA['goods_price'];
                $tA['goods_price'] = sprintf('%.2f',($tA['goods_price'] * $tA['discount'])/10);
            }
		}
		
		return $tA;
	}
	
	/**
	 * 保存 | 修改 产品
	 * @param array $data 数据
	 * @param number $id  id
	 * @return boolean|boolean|number
	 * @author zyl
	 */
	public function save($data,$id = 0){
		if ($id){
			$this->db->where('id',$id);
			$query = $this->update($this->tbProduct, $data);
			return $query === false ? false : true;
		}else{
			return $this->insert($this->tbProduct, $data);
		}
	}

    /**
     * 批量保存产品
     * @param $data
     * @param string $key
     * @return bool
     */
    public function saveBatchProduct($data,$key = ''){
        if ($key){
            return $this->updateBatch($this->tbProduct, $data, $key);
        }
        return $this->insertBatch($this->tbProduct, $data);
    }


	/**
	 * 批量获取产品 通过ids
	 * @param array     $tProductIds ids
	 * @param integer   $merchantId
	 * @return array
	 * @author zyl
	 */
	public function getProductByIds($tProductIds,$merchantId = 0){
		if ( ! $tProductIds){
			return array();
		}
		
		if ($merchantId){
			$this->db->where('merchant_id',$merchantId);
		}
		
		$this->db
		->select('id,name,merchant_id,icon,goods_price,sale_quantity')
		->where_in('id',$tProductIds);
	
		$tA = $this->getAll($this->tbProduct);

		$tData = array();
		foreach ($tA as $k=>$v){
			$v['icon'] = getImage($v['icon']);
			$tData[$v['id']] = $v;
		}
		
		return $tData;
	}
	
	/**
	 * 获取变体
	 * @param array $param
	 * @return array
	 * @author zyl
	 */
	public function getPreviewList($param = array(),$merchantId = 0){
		
		$tProductIds = array();
		foreach ($param as $k=>$v){
			if (! $k){
				//第一个
				$this->db->where(array('product_id'=>$v['product_id'],'sort'=>$v['variant_sort']));
			}else{
				//第N个
				$this->db->or_where(array('product_id'=>$v['product_id']));
				$this->db->where('sort',$v['variant_sort']);
			}
			
			if (!in_array($v['product_id'], $tProductIds)){
				$tProductIds[] = $v['product_id'];
			}
		}
		
		$tA = $this->getAll($this->tbProductVariant);
		
		//获取变体
		if ( ! $tA){
			return array();
		}
		
		$tVariant = array();
		foreach ($tA as $k=>$v){
			$tVariant[$v['product_id']][$v['sort']] = $v;
		}
		
		if ( ! $tVariant){
			return array();
		}
		
		//获取产品
		$tProduct = $this->getProductByIds($tProductIds,$merchantId);
		if ( ! $tProduct){
			return array();
		}
		
		$tParam = array();
		foreach ($param as $k=>$v){
			
			if ( ! isset($tProduct[$v['product_id']])){
				continue;
			}
			
			$tParam[] = array(
					'id'=>$v['product_id'],
					'name'=>$tProduct[$v['product_id']]['name'],
					'icon' =>$tProduct[$v['product_id']]['icon'],
					'property'=>json_decode($tVariant[$v['product_id']][$v['variant_sort']]['property'],true),
					'_property'=>implode(json_decode($tVariant[$v['product_id']][$v['variant_sort']]['property'],true), '/'),
					'price' =>isset($tVariant[$v['product_id']][$v['variant_sort']]) 
					? $tVariant[$v['product_id']][$v['variant_sort']]['price'] : $tProduct[$v['product_id']]['goods_price'],//变体价格 ? 变体价格 : 原价
					'number'=>(string)$v['number'],
			);
		}
		
		return $tParam;
	}
	
	/**
	 * 移除产品
	 */
	static public function remove(){
		
	}

    /**
     * 统计产品数量
     * @param int $time
     * @param array $ci
     * @return array
     * @author heyu
     */
    public function getTotalProduct($time = 0, $ci = array()){
        if ($time){
            $this->db->where('p.addtime > '.$time);
        }
        if (!empty($ci)){
            get_instance()->loadModel('MerchantUserModel', 'mMerchant', 'merchant');
            $this->db->join($this->mMerchant->tbShop.' s', 'p.merchant_id=s.merchant_id')
                ->where_in('s.county', $ci);
        }
        $this->db->where('p.status > -1');
        return $this->count($this->tbProduct.' p');
    }

    /**
     * 商家上架中的商品
     * @param int $time
     * @param array $ci
     * @return array
     * @author zyl
     */
    public function getTotalProductByMerchantId($merchantId){
    	$this->db->where('p.merchant_id',$merchantId);
    	$this->db->where('p.status',2);
    	return $this->count($this->tbProduct.' p');
    }
    
    /**
     * 获取商户前30天，销量
     * @param array $merchantIds
     * @return mixed
     * @author zyl
     */
    public function getSaleQuantityByMonth($merchantIds){
    	
    	$this->db->select('o.merchant_id,sum(op.quantity) as total_quantity')
    	->join($this->tbOrderProduct.' op','op.order_id = o.id','left')
    	->where_in('o.merchant_id',$merchantIds)
    	->where('o.status',5)
    	->where('o.addtime > ',strtotime('- 30 day',time()))
    	->group_by('o.merchant_id');//前30天
    	$tA = $this->getAll($this->tbOrder.' o');
    	
    	$tData = array();
    	if ( ! $tA){
    		foreach ($merchantIds as $k=>$v){
    			$tData[$v] = array("total_quantity"=>"0");
    		}
    		return $tData;
    	}
    	
    	foreach ($tA as $k=>$v){
    		$tData[$v['merchant_id']] = $v;
    	}
    	
    	return $tData;
    }
	/////////////////////////////////////////////////
	//+----------------------------------------------
	//|	商品标签属性
	//+----------------------------------------------
	
	/**
	 * 获取该商品标签总数
	 * @param integer $productId 商品id
	 * @author zyl
	 * @return integer 数量
	 */
	public function getTotalProperty($productId){
		if ( ! $productId){
			return 0;
		}
		$this->db->where('product_id',$productId);
		return $this->count($this->tbProductProperty);
	}
	
	/**
	 * 获取产品标签列表
	 * @param integer $productId 产品id
	 * @return array
	 * @author zyl
	 */
	public function getPropertyList($productId){
		if ( ! $productId){
			return array();
		}
		$this->db->where('product_id',$productId);
		$this->db->order_by('sort asc');
		$tA = $this->getAll($this->tbProductProperty);
		
		foreach ($tA as $k=>$v){
			$tA[$k]['value'] = explode('|', $v['value']);
		}
		
		return $tA;
	}
	
	/**
	 * 获取产品标签列表
	 * @param integer $productId 产品id
	 * @return array
	 * @author zyl
	 */
	public function getPropertyListByIds($productIds){
		if ( ! $productIds){
			return array();
		}
		$this->db->select('product_id,lable,value,sort');
		$this->db->where_in('product_id',$productIds);
		$this->db->order_by('sort asc');
		$tA = $this->getAll($this->tbProductProperty);
		
		$tData = array();
		foreach ($tA as $k=>$v){
			$v['value'] = explode('|', $v['value']);
			$tData[$v['product_id']][] = $v;
		}
		
		return $tData;
	}
	
	/**
	 * 交叉组合变体
	 * @param array $tA	属性单个数组
	 * @param array $DATA	组合后的数组
	 * @return unknown[]
	 * @author zyl
	 */
	private function arrayProperty($tA = array(),$DATA = array()){
		$tData = array();

		foreach ($tA['value'] as $k=>$v){
			if ($DATA){
				foreach ($DATA as $kk=>$vv){
					$vv[$tA['sort']] = $v;
					$tData[] = $vv;
				}
			}else{
				$temp[$tA['sort']] = $v;
				$tData[] = $temp;
			}
		}
		
		return $tData;
	}
	
	
	/**
	 * 获取产品标签信息
	 * @param integer $id 产品id
	 * @return array
	 * @author zyl
	 */
	public function getPropertyInfo($id){
		if ( ! $id){
			return array();
		}
		$this->db->where('id',$id);
		return $this->getOne($this->tbProductProperty);
	}
	
	/**
	 * 删除商品属性
	 * @param integer $id	id
	 * @param integer $productId	id
	 * @return array|boolean
	 * @author zyl
	 */
	public function removeProperty($id,$productId = 0){
		if ( ! $id && ! $productId){
			return array();
		}
		if ($id){
			$this->db->where('id',$id);
		}
		if ($productId){
			$this->db->where('product_id',$productId);
		}
		return $this->delete($this->tbProductProperty);
	}
	
	/**
	 * 保存 | 修改 产品
	 * @param array $data 数据
	 * @param number $id  id
	 * @return boolean|boolean|number
	 * @author zyl
	 */
	public function saveProperty($data,$id = 0,$batch = FALSE){
		if ($batch){
			return $this->insertBatch($this->tbProductProperty, $data);
		}else{
			return $this->insert($this->tbProductProperty, $data);
		}
	}
	
	
	/////////////////////////////////////////////////
	//+----------------------------------------------
	//|	商品详情
	//+----------------------------------------------
	
	/**
	 * 删除商品属性
	 * @param integer $id	id
	 * @return array|boolean
	 * @author zyl
	 */
	public function removeDetail($productId = 0,$sort = 0){
		if ( ! $sort && ! $productId){
			return array();
		}
		if ($sort){
			$this->db->where('sort',$sort);
		}
		if ($productId){
			$this->db->where('product_id',$productId);
		}
		return $this->delete($this->tbProductDetail);
	}
	
	/**
	 * 保存 | 修改 产品
	 * @param array $data 数据
	 * @param number $id  id
	 * @return boolean|boolean|number
	 * @author zyl
	 */
	public function saveDetail($data,$productId = 0,$sort = 0,$batch = FALSE){
		if ($productId && $sort){
			$this->db->where(array('product_id'=>$productId,'sort'=>$sort));
			$query = $this->update($this->tbProductDetail, $data);
			return $query === false ? false : true;
		}else if ($batch){
			return $this->insertBatch($this->tbProductDetail, $data);
		}else{
			return $this->insert($this->tbProductDetail, $data);
		}
	}
	
	/**
	 * 获取产品标签列表
	 * @param integer $productId 产品id
	 * @return array
	 * @author zyl
	 */
	public function getDetailList($productId,$type = 0){
		if ( ! $productId){
			return array();
		}
		if ($type){
			$this->db->where('type',$type);
		}
		$this->db->select('type,sort,content');
		$this->db->where('product_id',$productId);
		$this->db->order_by('sort asc');
		$tA = $this->getAll($this->tbProductDetail);

		if($tA){
		    foreach ($tA as $k=>$v){
		        if($v['type'] == 2){
		            $tA[$k]['imgs'] = $v['content'];
		            $tA[$k]['content'] = getImage($v['content'],'og');
                }
            }
        }
		return $tA;
	}
	
	/////////////////////////////////////////////////
	//+----------------------------------------------
	//|	商品变体
	//+----------------------------------------------
	
	/**
	 * 获取产品标签信息
	 * @param integer $id 产品id
	 * @return array
	 * @author zyl
	 */
	public function getPropertyVariantInfo($productId,$sort){
		if ( ! $productId || ! $sort){
			return array();
		}
		$this->db->where('product_id',$productId);
		$this->db->where('sort',$sort);
		$tA = $this->getOne($this->tbProductVariant);
		$tA['quantity'] = $tA['is_limited'] == 2?'999':$tA['quantity'];//库存量如果是无限的话，就设置为999
		return $tA;
	}
	
	/**
	 * 保存 | 修改 产品
	 * @param array $data 数据
	 * @param number $id  id
	 * @return boolean|boolean|number
	 * @author zyl
	 */
	public function savePropertyVariant($data,$productId = 0,$sort = 0,$batch = FALSE){
		if ($productId && $sort){
			$this->db->where(array('product_id'=>$productId,'sort'=>$sort));
			$query = $this->update($this->tbProductVariant, $data);
			return $query === false ? false : true;
		}else if ($batch){
			return $this->insertBatch($this->tbProductVariant, $data);
		}else{
			return $this->insert($this->tbProductVariant, $data);
		}
	}
	
	/**
	 * 删除商品属性
	 * @param integer $id	id
	 * @return array|boolean
	 * @author zyl
	 */
	public function removePropertyVariant($id,$productId = 0){
		if ( ! $id && ! $productId){
			return array();
		}
		if ($id){
			$this->db->where('id',$id);
		}
		if ($productId){
			$this->db->where('product_id',$productId);
		}
		return $this->delete($this->tbProductVariant);
	}
	
	/**
	 * 获取产品标签组合列表
	 * @param integer $productId 产品id
	 * @return array
	 * @author zyl
	 */
	public function getPropertyVariantList($productId){
		if ( ! $productId){
			return array();
		}
		$this->db->where('product_id',$productId);
		$this->db->order_by('sort asc');
		$tA = $this->getAll($this->tbProductVariant);

		$tData = array();
		foreach ($tA as $k=>$v){
			$v['property'] = json_decode($v['property'],true);
			$temp = array();
			foreach ($v['property'] as $kk=>$vv){
				$temp[] = array('key'=>$kk,'value'=>$vv);
			}
			$v['property'] = $temp;
			// 			unset($v['sale_quantity']);
			// 			unset($v['quantity']);
			// 			unset($v['sort']);
			// 			unset($v['status']);
			$productId = $v['product_id'];
			unset($v['product_id']);
			$v['quantity'] = $v['is_limited'] == 2?'999':$v['quantity'];//库存量如果是无限的话，就设置为999
			$tData[] = $v;
		}
		
		return $tData;
	}
	
	/**
	 * 获取产品标签组合列表
	 * @param integer $productId 产品id
	 * @return array
	 * @author zyl
	 */
	public function getPropertyVariantListByIds($productIds){
		if ( ! $productIds){
			return array();
		}
		$this->db->select('product_id,property,quantity,is_limited')
		->where_in('product_id',$productIds);
		$this->db->order_by('sort asc');
		$tA = $this->getAll($this->tbProductVariant);
		
		$tData = array();
		foreach ($tA as $k=>$v){
			$v['property'] = json_decode($v['property'],true);
			$temp = array();
			foreach ($v['property'] as $kk=>$vv){
				$temp[] = array('key'=>$kk,'value'=>$vv);
			}
			$v['property'] = $temp;
// 			unset($v['sale_quantity']);
// 			unset($v['quantity']);
// 			unset($v['sort']);
// 			unset($v['status']);
			$productId = $v['product_id'];
			unset($v['product_id']);
			$tData[$productId][] = $v;
		}
		return $tData;
	}
	
	/**
	 * 获取属性组合
	 * @param array $tAProperty
	 * @param array $variant
	 * @return unknown[]|array[]|unknown[][]
	 * @author zyl
	 */
	public function setPropertyVariant($tAProperty = array(),$variant = array()){
		
		$tData = array();
		$tVariant = array();
		
		foreach ($tAProperty as $tK=>$tV){
			$tData = $this->arrayProperty($tV,$tData);
		}
		
		if ($variant){
			//合并变体值
			foreach ($tData as $k=>$v){
				$isFind = false;
				foreach ($variant as $kk=>$vv){
					if( ! array_diff($v,$vv['property'])){
						$tVariant[] = $vv;
						$isFind = true;
						break;
					}
				}
				if ( ! $isFind){
					$tVariant[] = $v;
				}
			}
		}else{
			$tVariant = $tData;
		}
		
		return $tVariant;
	}

	/**********************属性**********************/

    /**
     * 删除商品属性
     * @param integer $id	id
     * @param integer $productId	id
     * @return array|boolean
     */
    public function removeTags($id,$productId = 0){
        if ( ! $id && ! $productId){
            return array();
        }
        if ($id){
            $this->db->where('id',$id);
        }
        if ($productId){
            $this->db->where('product_id',$productId);
        }
        return $this->delete($this->tbTags);
    }

    /**
     * 保存 | 修改 产品
     * @param array $data 数据
     * @param bool $batch
     * @return boolean|boolean|number
     * @author zyl
     */
    public function saveTags($data,$batch = false){
        if ($batch){
            return $this->insertBatch($this->tbTags, $data);
        }else{
            return $this->insert($this->tbTags, $data);
        }
    }

    /**
     * 获取产品标签列表
     * @param integer $productId 产品id
     * @return array
     * @author zyl
     */
    public function getTagsList($productId){
        if ( ! $productId){
            return array();
        }
        $this->db->where('product_id',$productId);
        $this->db->order_by('sort asc');
        $tA = $this->getAll($this->tbTags);

        foreach ($tA as $k=>$v){
            $tag_value = json_decode($v['tag_value'], true);
            $tA[$k]['tag_value'] = $tag_value;
            $tA[$k]['tag_value_str'] = implode(',', $tag_value);
        }

        return $tA;
    }
    /**
     * 获取产品标签列表
     * @param integer $productIds 产品id
     * @return array
     * @author zyl
     */
    public function getTagsListByIds($productIds){
        if ( ! $productIds){
            return array();
        }
        $this->db->where_in('product_id',$productIds);
        $this->db->order_by('sort asc');
        $tA = $this->getAll($this->tbTags);
        $temp = [];

        foreach ($tA as $k=>$v){

            $tag = '';
            if($v['tag_value']){
                $tag = implode(',',json_decode($v['tag_value'], true));
            }

            $temp[$v['product_id']][]= [
                'product_id' => $v['product_id'],
                'sort' => $v['sort'],
                'tag_name' => $v['tag_name'],
                'tag_value' => $tag,
            ];
        }

        return $temp;
    }

	/////////////////////////////////////////////////
	//+----------------------------------------------
	//|	后台方法
	//+----------------------------------------------
	
	/**
	 * 获取产品列表
	 * @param  array        $ids
	 * @return array
	 */
	public function adminGetList($ids = array()){
        $merchantId = (int)get('merchant_id');
        $merchantName = get('merchant_name');
        $categoryName = trim(get('order_category_name'));
        $name = trim(get('name'));
        $customCatagoryId = (int)get('custom_category_id'); //商家分类id
        $parentId = (int)get('parent_id'); //平台一级分类id
        $categoryId = (int)get('category_id'); //平台二级分类id
        $isLimited = (int)get('is_limited');
        $goodsPrice = trim(get('goods_price'));
        $sendDateFrom = strtotime(get('pro_send_date_from'));
        $sendDateTo = strtotime(get('pro_send_date_to'));
        $status = (int)get('pro_status');
        $iSortCol_0 = (int)get('iSortCol_0');//针对某一列进行排序
        $sSortDir_0 = trim(get('sSortDir_0'));//排序方式，值为"asc"或者"desc"

        if ($merchantName){
            get_instance()->loadModel('MerchantUserModel', 'mMerchant', 'merchant');
            $info = $this->mMerchant->getInfoByLikeName($merchantName);

            if (empty($info)){
                $this->db->where_in('p.merchant_id', array(0));
            }else{
                $merIds = array();
                foreach ($info as $k => $v){
                    if (!in_array($v['id'], $merIds)){
                        $merIds[] = $v['id'];
                    }
                }
                $this->db->where_in('p.merchant_id', $merIds);
            }
        }
        if ($ids){
            $this->db->where_in('p.merchant_id', $ids);
        }
	    if ($merchantId){
	        $this->db->where(array('p.merchant_id' => $merchantId));
        }
        if ($name){
	        $this->db->like(array('p.name' => $name));
        }
        if ($categoryName){
            $this->db->where('(c.cat_name like "%'.$categoryName.'%" or cg.cat_name like "%'.$categoryName.'%" or pcc.cat_name like "%'.$categoryName.'%")');
        }
        if ($parentId){
            $this->db->where(array('c.id' => $parentId));
        }
        if ($categoryId){
            $this->db->where(array('cg.id' => $categoryId));
        }
        if ($customCatagoryId){
            $this->db->where(array('pcc.id' => $customCatagoryId));
        }
        if ($isLimited){
	        $this->db->where(array('p.is_limited' => $isLimited));
        }
        if ($goodsPrice){
	        $this->db->like(array('p.goods_price' => $goodsPrice));
        }
        if ($status){
            $status -= 1;
	        $this->db->where(array('p.status' => $status));
        }else{
            $this->db->where('p.status > -1');
        }
        if($sendDateFrom){
            $this->db->where('p.addtime >=', $sendDateFrom);
        }
        if($sendDateTo){
            $this->db->where('p.addtime <= ', strtotime('+1day', $sendDateTo));
        }
        if ($iSortCol_0 == 5){
            $this->db->order_by('p.goods_price', $sSortDir_0);

        }else if($iSortCol_0 == 6){
            $this->db->order_by('p.sale_quantity', $sSortDir_0);
        }else if($iSortCol_0 == 7){
            $this->db->order_by('p.quantity', $sSortDir_0);
        }else if($iSortCol_0 == 8){
            $this->db->order_by('p.addtime', $sSortDir_0);
        }else{
            $this->db->order_by('p.addtime desc');
        }

		$this->db->select('p.id,p.icon,p.merchant_id,p.name,pcc.cat_name,p.goods_price,c.cat_name as parent_name,
						cg.cat_name as category_name,p.market_price,p.sale_quantity,p.quantity,p.addtime,p.status,
						p.is_limited')
		    ->join($this->tbProductCustomCategory.' pcc','pcc.id = p.category_id')
		    ->join($this->tbCategory.' c','c.id = pcc.parent_id')
		    ->join($this->tbCategory.' cg','cg.id = pcc.category_id');
		return $this->pagination($this->tbProduct.' p');
	}
	
	/**
	 * 获取规格组合列表
     * @param $productId    int
	 * @return array
	 */
	public function adminGetVariantList($productId = 0){
        $iSortCol_0 = (int)get('iSortCol_0');//针对某一列进行排序
        $sSortDir_0 = trim(get('sSortDir_0'));//排序方式，值为"asc"或者"desc"

        if ($iSortCol_0 == 1){
            $this->db->order_by('price', $sSortDir_0); // 价格
        }else if($iSortCol_0 == 2){
            $this->db->order_by('quantity', $sSortDir_0); // 库存
        }else if($iSortCol_0 == 3){
            $this->db->order_by('sale_quantity', $sSortDir_0); // 销量
        }else{
            $this->db->order_by('status desc,sort asc');
        }

		$this->db->select('property,price,quantity,sale_quantity,sort,is_limited,status');
		if ($productId){
			$this->db->where('product_id',$productId);
		}
		return $this->pagination($this->tbProductVariant);
	}

    /**
     * 查看分类下的商品总数
     * @param $id   int     分类id
     * @return array|int
     * @author heyu
     */
	public function getProductTotalByCategoryId($id){
	    if (!$id){
	        return 0;
        }
        $this->db->where(array('category_id' => $id));
	    return $this->count($this->tbProduct);
    }

    /**
     * 删除商品
     * @param $id
     * @return bool
     * @author heyu
     */
    public function deleteProduct($id){
        if (!$id){
            return false;
        }
        $this->db->where(array('id' => $id));
        return $this->delete($this->tbProduct);
    }

    /**
     * 获取状态显示样式
     * @param int $status
     * @param bool $show
     * @return array|mixed|string
     * @author heyu
     */
    public function getStatus($status = -1, $show = false){
        $config = array(0 => '草稿', 1 => '下架', 2 => '上架');
        if($status < 0){
            return $config;
        }

        if($status && ! isset($config[$status])){
            return '';
        }

        if( ! $show){
            return $config[$status];
        }

        if($status == 0){
            return '<span class="label label-warning">'.$config[$status].'</span>';
        }else if($status == 1){
            return '<span class="label label-danger">'.$config[$status].'</span>';
        }else if($status == 2){
            return '<span class="label label-success">'.$config[$status].'</span>';
        }
        return'';
    }
    
    /**
     * 判断商品是否可以下单
     * 
     * @param	integer	会员id
     * @param 	array 	$product  [['product_id' => 1, 'sort' => 1, 'quantity' => 1, 'price' => 1, 'tags' => $tags]]
     * @return	mixed	false:数据格式错误|array：可以下单|string：错误描述
     * @author	lhp
     */
    public function canAddOrder($userId, $product, $isAddCart = false, $delete = false){
   		
    	if( ! is_array($product) || ! (bool)$product){
    		return false;
    	}

    	//验证参数类型是否正确和获取所有的产品id
    	$productId = array();
    	$quantity = array();
    	$price = array();
    	foreach ($product as $v){
    		
	    	if( ! isset($v['product_id']) || ! is_numeric($v['product_id']) || strpos($v['product_id'], '.')){
	    		return false;		
	    	}		
	    	
	    	if(isset($v['sort']) && (! is_numeric($v['sort']) || strpos($v['sort'], '.'))){
	    		return false;		
	    	}		
	    	
	    	if( ! isset($v['quantity']) || ! is_numeric($v['quantity']) || strpos($v['quantity'], '.')){
	    		return false;		
	    	}
	    	
	    	if(isset($v['price']) && ! is_numeric($v['price'])){
	    		return false;		
	    	}
	    	
	    	$productId[] = $v['product_id'];
	    	$quantity[$v['product_id']] = $v['quantity'];
	    	if (isset($v['price'])){
	    		//如果价格存在则添加
		    	$price[$v['product_id']][$v['sort']] = isset($v['price']) ? $v['price'] : 0;
	    	}
    	}
    	
    	//判断购物车里面是否存在
    	if ($productId){
    		
    	}

    	//判断产品是否有规格
    	$hasVariant = $this->hasVariant($productId);
    	$tempProduct = [];
    	foreach ($product as $v){
            //产品有规格，但是没有传产品规格
            if($hasVariant[$v['product_id']] && ! isset($v['sort'])){
                return false;
            }
            //没有规格但是传了规格id
            if( ! $hasVariant[$v['product_id']] && (isset($v['sort']) && $v['sort'] > 0) ){
                return false;
            }
            $tempProduct[$v['product_id']] = $v;
    	}

    	//获取产品数据
    	$this->db->select('p.id,p.icon,p.name,p.is_special,p.is_free_shipping,p.weight,p.merchant_id,p.goods_price,p.market_price,p.is_limited,p.quantity,
    					,p.limit_number,p.discount,p.status,IFNULL(p.lunch_box_fee,0) as lunch_box_fee,
    					v.property,v.price as v_price,v.quantity as v_quantity,v.sort,v.status as v_status,
    					v.is_limited as v_is_limited,v.sort as variant_id,v.sale_quantity,v.weight as v_weight')
    			 ->join($this->tbProductVariant.' v', 'v.product_id = p.id', 'left');
    	$where = '';
    	foreach ($product as $v){
			
    		if( ! $where){
    			if( ! $hasVariant[$v['product_id']]){
    				$where = '(p.id = '.$v['product_id'].' and v.sort is null)';
    			}else{
	    			$where = '(p.id = '.$v['product_id'].' and v.sort ='.$v['sort'].')';
    			}
    		}else{
    			if( ! $hasVariant[$v['product_id']]){
    				$where .= ' or (p.id = '.$v['product_id'].' and v.sort is null)';
    			}else{
    				$where .= ' or (p.id = '.$v['product_id'].' and v.sort ='.$v['sort'].')';
    			}
    		}
    	}

    	$this->db->where($where);
    	$dbProduct = $this->getAll($this->tbProduct.' p');

		//判断产品是否可以下单
    	if(count($dbProduct) != count($product)){
    		exit(json_encode($product));
    		return false;			
    	}

    	$restrictions = []; //限购产品
    	$restrictionsProductId = [];
    	$unsale = '';
    	foreach ($dbProduct as $k => &$v){
    		
    		//判断产品状态
    		if($v['status'] == 1){
//    		    //删除购物车商品
//                get_instance()->loadModel('ConsumerCartModel', 'mCart', 'consumer');
//                $this->mCart->deleteCartProduct($userId, $v['id']);
//    			return $v['name'].'已经下架';
                $unsale .= $v['name'].',';

    		}elseif($v['status'] != 2){
    			return $v['name'].'未上架';
    		}	
    		
    		//判断规格状态
    		$variant = json_decode($v['property'], true);
    		$name = $v['name'];
    		if($v['v_status'] == 1){
    			$name = $v['name'].'（'.implode('/', $variant).'）';
    			return  $name.'已删除';
    		}
            if($v['limit_number'] > 0){
                $restrictions[$v['id']] = $v['limit_number'];
                $restrictionsProductId[] = $v['id'];
                $v['market_price'] = $v['goods_price'];
                $v['v_price'] = sprintf('%.2f',$v['v_price']*$v['discount']/10);
                $v['goods_price'] = sprintf('%.2f',$v['goods_price']*$v['discount']/10);

            }
            if($v['sort'] > 0){
                $v['goods_price'] = $v['v_price'];
                $v['weight'] = $v['v_weight'];
            }
    		//判断库存和价格变化情况
    		if($hasVariant[$v['id']]){
	    		if($v['v_is_limited'] == 1 && $v['v_quantity'] < $quantity[$v['id']] && $delete == false){
	    			return  $name.'剩余库存不足';
	    		}
	    		
	    		if(isset($price[$v['id']][$v['sort']]) && $price[$v['id']][$v['sort']] != $v['v_price']){
	    			return  $name.'价格发生了变化，请重新下单';
	    		}
    		}else{
    			
    			if($v['is_limited'] == 1 && $v['quantity'] < $quantity[$v['id']] && $delete == false){
    				return  $name.'剩余库存不足';
    			}
    			
    			if(isset($price[$v['id']][0]) && $price[$v['id']][0] != $v['goods_price']){
//     				return  json_encode($price);
    				return  $name.'价格发生了变化，请重新下单';
    			}
    		}



    		//我购买的数量
    		if (isset($quantity[$v['id']])){
    			$dbProduct[$k]['b_quantity'] = $quantity[$v['id']];
    		}
            //商品属性
            $dbProduct[$k]['tags'] = isset($tempProduct[$v['id']]['tags'])?$tempProduct[$v['id']]['tags']:'';
    	}
        //判断下架商品
        if($unsale){
    	    $unsale = '该商品已下架-'.$unsale;
    	    return $unsale;
        }
    	//判断限购商品
    	if($restrictionsProductId){
	    	$tA = $this->getCartAndOrderQuantity($userId, $restrictionsProductId, ($isAddCart ? false : true));

	    	foreach ($tA as $kk => $vv){

                $tI = $restrictions[$kk] - $vv;
	    		if($restrictions[$kk] - $vv < $quantity[$kk]){

//                    if($tI <= 0){
//                        return $name.'已限购，你不能够买该商品了';
//                    }

	    			if($isAddCart){

                        if($tI <= 0 && $delete == false){
//                            return $name.'已限购，你不能够买该商品了';
                            return '该商品已限购，你还可以看看其他商品哦';
                        }
                        if($restrictions[$kk] < $quantity[$kk] && $delete == false){
//                            return $name.'已限购，你只能最多购买'.$restrictions[$kk].'件';
                            return '该商品已限购，你只能购买'.$restrictions[$kk].'件哦';
                        }

//                        return $name.'已限购，你不能够买该商品了';
//	    				return '你还能加入'.($tI).'件该商品到购物车';
	    			}else{
	    			    if($delete == false){
                            if($tI <= 0 ){
//		    				return $name.'已限购，你不能够买该商品了';
                                return '该商品已限购，你还可以看看其他商品哦';
                            }else{
//	    					return $name.'已限购，你只能最多购买'.$tI.'件';
                                return '该商品已限购，你只能购买'.$tI.'件哦';
                            }
                        }

	    			}
	    		}
	    	}
    	}


    	return $dbProduct;
    }
    
    /**
     * 获取购物车和订单商品的总数
     * @param 	integer 	$userId		购买商品的总数
     * @param 	string 		$onlyOrder
     * @return	mixed
     * @author	lhp
     */
    public function getCartAndOrderQuantity($userId, $productId, $onlyOrder = true){

		$time = strtotime(date('Y-m-d'));
		$end = $time + 86400;
    	$this->db->select('p.product_id,sum(p.quantity) as number')
    			 ->join($this->tbOrder.' o', 'o.id = p.order_id')
    			 ->where('o.consumer_id', $userId)
    			 ->where('((o.status = 1 and addtime>'.$time.' and addtime<'.$end.') or
    			            (o.status in(2,3,4,5) and pay_time >'.$time.' and pay_time <'.$end.'))')
//    			 ->where_in('o.status', [2,3,4,5,6])
    			 ->where_in('p.product_id', $productId)
    			 ->group_by('p.product_id');
    	
    	$order = [];
    	$tA = $this->getAll($this->tbOrderProduct.' p'); 
    	foreach ($tA as $v){
    		$order[$v['product_id']] = $v['number'];
    	}
    	
    	if($onlyOrder){
    		return $order;
    	}
    	
    	$this->db
    		->select('product_id,sum(quantity) as number')
    		->where_in('product_id', $productId)
    		->where('consumer_id', $userId)
    		->group_by('product_id');
		    	
    	$tA = $this->getAll($this->tbCart.' c');
    	$cart = [];
    	foreach ($tA as $v){
    		$cart[$v['product_id']] = $v['number'];
    	}
    	
    	$data = [];
    	foreach ($productId as $v){
    		$data[$v] = (isset($cart[$v]) ? $cart[$v] : 0) + (isset($order[$v]) ? $order[$v] : 0);
    	}
    	
    	return $data;
    }
    
    /**
     * 判断商品是否有规格
     * @param mixed 	$id
     * @return mixed	
     */
    public function hasVariant($id, $sortId = 0){
    	
    	if(is_array($id)){
    		$this->db->select('product_id')
    				 ->where_in('product_id', $id)
    				 ->group_by('product_id');
    		
    		$tA = $this->getAll($this->tbProductVariant);
    		$productId = [];
    		foreach ($tA as $v){
    			$productId[] = $v['product_id'];
    		}
    		
    		$data = [];
    		foreach ($id as $v){
    			$data[$v] = in_array($v, $productId) ? true : false;
    		}
    		
    		return $data;
    	}
    	
    	$this->db->where('product_id', $id);
    	if($sortId){
    		$this->db->where('sort', $sortId);
    	}
    	$tI = $this->count($this->tbProductVariant);
    	if($tI){
    		return true;
    	}
    	return false;
    }

    /**
     * 多规格商品剩余库存是否大于0
     */
    public function hasQuantity($id, $sortId = 0){

        $this->db->select('is_limited,quantity')
            ->where('product_id', $id);

        if($sortId){
            $this->db->where('sort <>', $sortId);
        }
        $tA = $this->getAll($this->tbProductVariant);
        if($tA){
            foreach ($tA as $v){
                if($v['is_limited'] == 2){
                    return true;
                }
                if($v['quantity']>0){
                    return true;
                }
            }
        }

        return false;
    }

    /**
     * 关键字搜索商家下的商品
     * @param $keyword      关键字
     * @param int $merchantId
     * @return array
     */
    public function getInfoByLikeName($keyword, $merchantId){
        if (! $keyword && !$merchantId){
            return array();
        }
        $this->db->select('id,name')
            ->where(array('status' => 2, 'merchant_id' => $merchantId))
            ->like('name', $keyword);
        return $this->getAll($this->tbProduct);
    }
}